<template>
	<view class="wanlshop-classify-container">
		<view class="wanlshop-classify-container__list">

			<!-- 左侧导航 -->
			<scroll-view scroll-y scroll-with-animation class="left" :scroll-top="scrollTop"
				:style="{ height: `${mainHeight}px` }">
				<view v-for="(item,index) in categoryData" :key="item.id" class="item"
					:class="[currentTab == index ? 'active' : '']" :data-current="index" :data-id="item.categoryId"
					@tap.stop="handleNav($event, item.id)">
					<text>{{ item.name }}</text>
				</view>
			</scroll-view>

			<!-- 分类内容区域 -->
			<block v-for="(item,index) in categoryData" :key="item.id">
				<scroll-view scroll-y refresher-enabled :refresher-triggered="triggered" :refresher-threshold="100"
					refresher-background="transparent" @refresherpulling="refresherpulling"
					@refresherrefresh="refresherrefresh" @refresherrestore="refresherrestore" @touchstart="touchStart"
					@touchend="touchEnd" class="right" style="min-width: 0;" :style="{ height: `${mainHeight}px` }"
					v-if="currentTab == index">

					<view class="text-status" v-if="triggered == true" :style="{ 'background-color': color }">
						<view v-if="categoryData[index-1]">
							下拉至上一分类 {{categoryData[index-1].name}}
						</view>
						<view v-else>已经到顶了哟~</view>
					</view>

					<view class="list-cat">
						<!-- 顶部活动图 -->
						<view class="top-activity">
							<image lazy-load class="radius-bock" v-if="activity"
								style="height: 170rpx;box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.2);"
								:src="$wanlshop.oss(activity.img_url, 350, 0, 1)" mode="aspectFill"
								@tap.stop="toActivity(activity)"></image>
						</view>

						<!-- 分类标题 -->
						<view class="margin-bottom-xs text-bold" style="font-size: 28rpx;color: #5b3834;">
							<image src="../../static/images/default/cart.png" mode="widthFix" class="cart"></image>
							{{item.name}}
							<image src="../../static/images/default/cart.png" mode="widthFix" class="cart"></image>
						</view>

						<!-- 商品列表 -->
						<view class="goods-list" v-if="goodsData.length">
							<view class="item" v-for="(item,index) in goodsData" :key="item.id" @tap="onGoods(item.id)">
								<view class="image">
									<view class="img-bg" :style="{background: `url(${$wanlshop.oss(item.image)})`}">
									</view>
								</view>
								<view class="content">
									<view class="content-top">
										<view class="title text-cut-2">
											{{item.title}}
										</view>
										<text class="desc">
											{{item.description}}
										</text>
									</view>

									<view class="content-bottom">
										<view class="text">
											<!-- 需要判断是否有折扣价 -->
											<!-- <view class="price active">￥<span>{{item.discount_price}}</span></view> -->
											<view class="price active">￥<span>{{item.price}}</span></view>

										</view>
										<view class="cart-icon">
											<image src="../../static/images/default/cart_icon.png" mode="widthFix">
											</image>
										</view>
									</view>
								</view>
							</view>

							<!-- 切换下一分类 -->
							<view class="next_category" v-if="categoryData[index+1]">
								上滑至下一分类 {{categoryData[index+1].name}}
							</view>
							<view class="next_category" v-else>没有更多了哟~</view>
						</view>
						<wanl-empty text="暂无相关产品" v-else></wanl-empty>
					</view>
				</scroll-view>
			</block>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'wanlShopClassify',
		props: {
			shopId: {
				type: Number,
				default: 0
			},
			categoryStyle: {
				type: Number,
				default: 1
			},
			mainHeight: {
				type: Number,
				default: 0
			},
			categoryData: {
				type: Array,
				default: () => {
					return []
				}
			},
			color: {
				type: String,
				default: ''
			},
		},
		data() {
			return {
				currentTab: 0, //预设当前项的值
				scrollTop: 0, //tab标题的滚动条位置
				goodsList: [], //分类商品列表
				category: [], //分类导航
				params: {
					search: '',
					sort: 'weigh',
					order: 'asc',
					page: 1,
					filter: {},
					op: {}
				}, // 获取商品列表参数
				reload: false, //判断是否上拉,
				activity: {}, // 分类活动
				goodsData: [], // 商品列表，
				touch: 0, // 记录开始触摸点位置,
				startScroll: 0, // 记录开始触摸时，滚动条位置
				rightScrollTop: 0, // 滚动条位置

				isLock: true, // 滚动锁

				tabHeight: 0,
				triggered: false,
			}
		},
		watch: {
			// 更新分类数据
			categoryData: {
				handler(now, old) {
					// console.log('now', now)
					this.reload = true;
					if (now.length) {
						console.log('class', now)
						this.params.filter.category_id = now[this.currentTab].id;
						this.loadData();
					}
				},
				immediate: true,
			}
		},
		mounted() {
			let sys = uni.getSystemInfoSync();
			this.tabHeight = sys.screenHeight - sys.safeArea.bottom;
			// console.log('sys', sys)
			// console.log('tabHeight', this.tabHeight)
		},
		methods: {
			//异步加载商品列表
			async loadData() {
				// 锁定进入下一分类
				this.isLock = true;
				this.params.type = 'goods';
				this.params.op.category_id = 'in';
				// console.log('params', this.params)
				this.$api.get({
					url: '/wanlshop/product/lists',
					data: this.params,
					success: res => {
						this.isLower = false;
						console.log('/wanlshop/product/lists', res)
						// this.status = 'more';
						uni.stopPullDownRefresh();
						// 插入活动
						this.activity = res.activity;
						// 插入商品列表
						this.goodsData = this.reload ? res.list.data : this.goodsData.concat(res.list
							.data); //数据 追加
						// this.params.page = res.current_page; //当前页码
						// this.last_page = res.last_page; //总页码
						// console.log('res2', this.goodsData)

						this.goodsData.reverse();

						setTimeout(() => {
							// 创建交叉观察者
							this.observer = uni.createIntersectionObserver(this);
							// 获取元素高度
							let query = uni.createSelectorQuery().in(this);
							query.select('.next_category').boundingClientRect((ele) => {
								console.log('qeruy', ele.height)

								this.observer.relativeToViewport({
									bottom: -(ele.height - 2)
								}).observe('.next_category', (res) => {
									console.log('createIntersectionObserver', res);
									if (res.intersectionRatio > 0) {
										this.isLock = false;
									} else {
										this.isLock = true;
									}
									console.log('isLock', this.isLock)
								})
							}).exec();

						}, 0)
					},
					loadingTip: '加载中',
					loadingDuration: 300
				});
			},
			// 点击标题切换当前页时改变样式
			handleNav(e, id) {
				this.reload = true;
				let cur = e.currentTarget.dataset.current;
				if (this.currentTab == cur) {
					return false;
				} else {
					this.currentTab = cur;
					this.checkCor();

					// 根据当前分类id 获取分类商品
					// console.log('id', id)
					this.params.filter.category_id = id;
					this.loadData();
				}
			},
			handleProduct(category_id, category_name) {
				if (this.shopId === 0) {
					this.$wanlshop.to(
						`/pages/product/list?data=${JSON.stringify({ category_id: category_id, category_name: category_name })}`
					);
				} else {
					this.$wanlshop.to(
						`/pages/shop/product/list?shop_id=${this.shopId}&category_id=${category_id}&category_name=${category_name}`
					);
				}
			},
			//判断当前滚动超过一屏时，设置tab标题滚动条。
			checkCor() {
				if (this.currentTab > 7) {
					this.scrollTop = 500;
				} else {
					this.scrollTop = 0;
				}
			},
			// 下拉加载
			refresherpulling(e) {
				console.log('自定义下拉刷新控件被下拉');
				if (e.detail.deltaY < 0) return // 防止上滑页面也触发下拉
				this.triggered = true;
			},
			refresherrefresh() {
				console.log('自定义下拉刷新被触发');
				setTimeout(() => {
					this.triggered = false;
					this.touchStartCategory();
				}, 500);
			},
			refresherrestore() {
				console.log('自定义下拉刷新被复位');
				this.triggered = 'restore'; // 需要重置
			},
			/* 上滑至下一分类 */
			touchStart(e) {
				// 记录开始触摸点位置
				this.touch = e.touches[0].clientY;
				// 记录开始触摸时，scroll滚动条位置
				this.startScroll = this.rightScrollTop;
			},
			touchEnd(e) {
				console.log('this.rightScrollTop', this.rightScrollTop)
				console.log('this.startScroll', this.startScroll)
				console.log('滑动方向', e.changedTouches[0].clientY - this.touch)
				// 判断滑动方向
				if (e.changedTouches[0].clientY - this.touch < 0 && !this.isLock) {
					// 判断是否最后一页
					if (this.categoryData[this.currentTab + 1]) {
						// console.log('this.rightScrollTop', this.rightScrollTop)
						// console.log('下一页')
						this.reload = true;
						this.currentTab++;
						this.params.filter.category_id = this.categoryData[this.currentTab].id;
						this.loadData();
					} else {
						console.log('最后一页')
					}
				}
			},
			touchStartCategory(e) {
				// 判断是否第一页
				if (this.categoryData[this.currentTab - 1]) {
					this.reload = true;
					this.currentTab--;
					this.params.filter.category_id = this.categoryData[this.currentTab].id;
					this.loadData();
				} else {
					console.log('到顶了');
					this.loadData();
				}
			},
			// 跳转活动页面
			toActivity(item) {
				this.$api.post({
					loadingTip: '加载中',
					url: `/wanlshop/activity/detail`,
					data: {
						type: 'category',
						type_id: item.category_id
					},
					success: result => {
						uni.navigateTo({
							url: `/pages/page/activityPage`,
							success: (res) => {
								res.eventChannel.emit('data', {
									activity: result?.title,
									productList: result?.categories || [],
									headerImage: result?.header_img,
									footerImage: result?.footer_img,
								})
							}
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.wanlshop-classify-container {
		&__one {
			padding-left: 25rpx;
			padding-right: 25rpx;
			padding-bottom: 100rpx;
			padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);

			image {
				width: 100%;
				height: 300rpx;
				border-radius: 15rpx;
				overflow: hidden;
			}

			.item {
				position: relative;
				display: flex;
				justify-content: center;
				margin-top: 25rpx;

				.category-title {
					font-size: 26rpx;
					position: absolute;
					bottom: 20rpx;
					border-radius: 10rpx;
					overflow: hidden;
					color: #666666;
					background-color: rgba(255, 255, 255, .6);
					width: 60%;
					text-align: center;
					padding: 4rpx 0;
				}
			}
		}

		&__grid {
			padding-bottom: 100rpx;
			padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);

			.cu-list {
				background-color: rgba(255, 255, 255, 0);

				&>.cu-item {
					padding: 25rpx 0;
					align-items: center;

					image {
						width: 160rpx;
						height: 160rpx;
						margin-bottom: 10rpx;
					}
				}
			}
		}

		&__list {
			display: flex;
			gap: 25rpx;

			.left {
				width: 180rpx;
				z-index: 10;
				background: transparent;
				padding-top: 8rpx;
				font-size: 24rpx;

				.item {
					width: 100%;
					height: 80rpx;
					box-sizing: border-box;
					display: flex;
					align-items: center;
					justify-content: center;
					font-weight: 400;
					margin-bottom: 20rpx;

					&.active {
						background-color: #D3A87B;
						border-radius: 0 8rpx 8rpx 0;
						// color: #ffffff;
						color: #5b3834;
					}
				}
			}

			.right {
				width: 100%;
				// padding-left: 25rpx;
				box-sizing: border-box;
				background-color: transparent;

				/* background-image: linear-gradient(#fff, #f2f2f2, #f4f4f4, #f6f6f6); */
				.list-cat {
					width: 100%;
					overflow: hidden;
					padding-top: 10rpx;
					//padding-right: 20rpx;
					box-sizing: border-box;

					.top-activity {
						margin-right: 20rpx;
						margin-bottom: 24rpx;
					}

					.text-bold {
						display: flex;
						align-items: center;
					}

					.cart {
						width: 28rpx;
						height: 28rpx;
						margin-top: 4rpx;
					}

					.cart:first-child {
						margin-right: 8rpx;
					}

					.cart:last-child {
						margin-left: 8rpx;
					}

					.goods-list {
						padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
						overflow: hidden;

						.item {
							display: flex;
							gap: 20rpx;
							//padding: 14rpx 0;
							margin: 24rpx 0;
							box-sizing: border-box;
							background-color: #ffffff;
							border-radius: 12rpx;

							.image {
								width: 196rpx;
								height: 196rpx;
								border-radius: 12rpx 0 0 12rpx;
								overflow: hidden;
								flex-shrink: 0;

								.img-bg {
									width: 100%;
									padding-top: 100%;
									background-size: cover !important;
									background-position: center !important;
								}
							}

							.content {
								flex: 1;
								display: flex;
								flex-direction: column;
								justify-content: space-between;
								padding-top: 14rpx;
								padding-right: 20rpx;
								padding-bottom: 12rpx;
								overflow: hidden;

								.content-top {
									overflow: hidden;

									.title {
										font-weight: bold;
										font-size: 24rpx !important;
										margin-bottom:16rpx;
									}

									.desc {
										display: block;
										font-size: 20rpx;
										color: #737373;
										text-overflow: ellipsis;
										white-space: nowrap;
										overflow: hidden;
										width: 100%;
									}
								}

								.content-bottom {
									display: flex;
									justify-content: space-between;
									align-items: end;
									position: relative;

									.text {
										display: flex;
										align-items: flex-end;
										gap: 15rpx;

										.price {
											font-size: 20rpx;
											color: #ACACAC;
											text-decoration: line-through;

											&.active {
												color: red;
												font-size: 20rpx;
												text-decoration: unset;

												span {
													font-size: 32rpx;
												}
											}
										}
									}

									.cart-icon {
										width: 48rpx;
										height: 48rpx;
										position: absolute;
										right: 0rpx;
										top: -6rpx;

										image {
											width: 100%;
											height: 100%;
											display: block;
										}
									}
								}
							}
						}

						.next_category {
							width: 100%;
							height: 120rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							font-size: 24rpx;
							// padding: 40rpx 0;
							// border: 2rpx solid red;
						}
					}
				}

				.screen-swiper {
					min-height: 180rpx;
					height: 180rpx;
					overflow: hidden;
				}

				.list-item {
					background: #ffffff;
					width: 100%;
					box-sizing: border-box;
					padding: 20rpx;
					margin-bottom: 20rpx;

					.title {
						color: #FF4F00;
					}
				}

				.list-container {
					/* padding-top: 20rpx; */
					display: flex;
					display: -webkit-flex;
					justify-content: flex-start;
					flex-direction: row;
					flex-wrap: wrap;
				}

				.list-box {
					width: 33.3333%;
					text-align: center;
					padding-top: 40rpx;
				}

				.list-image {
					width: 120rpx;
					height: 120rpx;
				}
			}
		}
	}

	.text-status {
		position: absolute;
		top: -66rpx;
		width: 100%;
		text-align: center;
	}
</style>